package cn.edu.zpark.security.springboot.service;

import cn.edu.zpark.security.springboot.dao.IUserDao;
import cn.edu.zpark.security.springboot.model.PermissionDto;
import cn.edu.zpark.security.springboot.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Administrator
 * @version 1.0
 **/
@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    private IUserDao userDao;

    //根据 账号查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 构建查询对象
        UserDto userDto = new UserDto();
        userDto.setUsername(username);
        // 查询数据
        List<UserDto> dtoList = userDao.select(userDto);
        if(dtoList == null || dtoList.size() <= 0){
            //如果用户查不到，返回null，由provider来抛出异常
            return null;
        }
        //根据用户的id查询用户的权限
        List<PermissionDto> permissionsList = userDao.findPermissionsByUserId(dtoList.get(0).getId());
        // 定义权限数组，用于存放一个用户所有权限
        String[] pers = new String[permissionsList.size()];
        // 循环取出权限内容
        for (int i = 0; i < permissionsList.size(); i++) {
            pers[i] = permissionsList.get(i).getCode();
        }
        UserDetails userDetails = User.withUsername(dtoList.get(0).getUsername()).password(dtoList.get(0).getPassword()).authorities(pers).build();

        return userDetails;
    }
}
